package com.lntea.netty.demo.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOClient {
	private Selector selector;
	
	public void initClient(String host,int port) throws IOException{
		SocketChannel channel = SocketChannel.open();
		channel.configureBlocking(false);
		
		this.selector = Selector.open();
		channel.connect(new InetSocketAddress(host, port));
		channel.register(selector, SelectionKey.OP_CONNECT);
	}
	
	public void listen() throws IOException{
		while(true){
			this.selector.select();
			Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
			while(ite.hasNext()){
				SelectionKey key = ite.next();
				ite.remove();
				if(key.isConnectable()){
					SocketChannel channel = (SocketChannel) key.channel();
					if(channel.isConnectionPending()){
						channel.finishConnect();
					}
					
					channel.configureBlocking(false);
					
					channel.write(ByteBuffer.wrap(new String("client send message").getBytes()));
					
					channel.register(selector, SelectionKey.OP_READ);
				}else if(key.isReadable()){
					read(key);
				}
			}
		}
	}
	
	private void read(SelectionKey key) throws IOException {
		SocketChannel channel = (SocketChannel) key.channel();
		ByteBuffer buf = ByteBuffer.allocate(48);
		channel.read(buf);
		byte[] data = buf.array();
		String msg = new String(data).trim();
		System.out.println(msg);
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		channel.write(ByteBuffer.wrap("client send message".getBytes()));
	}

	public static void main(String[] args) throws IOException {
		NIOClient client = new NIOClient();
		client.initClient("localhost",8000);
		client.listen();
	}
}
